﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	CacheListQuery.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Web.Caching;
using Microsoft.SharePoint;

namespace Smart.Common
{
	/// <summary>
	/// Cache for SPList items query. Should be used with list with rare change or with not sensitive data. Default timeout is 15 minutes.
	/// </summary>
	public static class CacheListQuery
	{
		public static TimeSpan DefaultListTimeout = new TimeSpan(0, 0, 15, 0);
		public static CacheItemPriority DefaultListPriority = CacheItemPriority.AboveNormal;

		public static string SPListItemCacheKey = "splc";

		public static object ListSyncLock = new object();

		public static TCollectionType Get<TItemType, TCollectionType>(SPWeb web, string key, string listTitleOrUrl, string query, Dictionary<string, object> properties,
																	  Func<SPListItem, TCollectionType, TItemType> itemConverter,
																	  Func<MetaList, SPList, TCollectionType> collectionCreator)
			where TCollectionType : class, IList<TItemType>
		{
			lock (ListSyncLock)
			{
				var res = (TCollectionType)SPServices.Cache.Get(key, null);

				if (res != null)
					return res;

				var mw = MetaCtx.GetWeb(web);

				var list = mw.List(web, listTitleOrUrl);

				var items = SPH.GetFilteredItems(list, query, 1000000, properties);

				res = items.Convert(mw.List(listTitleOrUrl), list, itemConverter, collectionCreator);

				SPServices.Cache.Set(key, res, DefaultListTimeout, DefaultListPriority);

				return res;
			}
		}
	}
}